package com.lengyue.imakiba.show;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import com.jfinal.core.Controller;
import com.lengyue.imakiba.data.Anime;
import com.lengyue.imakiba.data.AnimeInterface;
import com.lengyue.imakiba.data.Episode;
import com.lengyue.imakiba.data.Type;

public class AnimeInfo extends Controller implements AnimeInterface{
	public void index()
	{
		//导航栏动漫类型
		int animeId = getParaToInt("animeId");
		Anime anime = Anime.dao.findById(animeId);
		//设置动漫声优
		anime.put("cvs", anime.getCV());
		//动漫剧集
		List<Episode> episodes = Episode.dao.find("select * from episode where anime_id = ? order by num",animeId);
		//动漫类型
		List<Type> types = Type.dao.find("select * from type order by sort_no");
		//与当前动漫类型相同的动漫推荐
		String similarAnimesSql = "select DISTINCT a.* from anime a "
		+"LEFT JOIN episode e on a.id = e.anime_id "
		+"where a.id in ("
		+"SELECT at1.anime_id from anime_type at1 where at1.type_code in "
		+"(select at.type_code from anime_type at where at.anime_id = ?)"
		+") and a.id <> ? order by e.date desc Limit 0,5";
		List<Anime> similarAnimes = Anime.dao.find(similarAnimesSql, animeId,animeId);
		LinkedHashMap<String,ArrayList<HashMap<String,String>>> episodeUrls = getEpisodeUrls(episodes,"url1","url2","url3","url4","url5","url6");
		setAttr("anime", anime);
		setAttr("episodeUrls", episodeUrls);
		setAttr("types", types);
		setAttr("similarAnimes", similarAnimes);
		setAttr("coverPath", coverPath);
		render("/WEB-INF/freeMarkerTemplete/anime_info.ftl");
	}
	/**
	 * 取动漫视频路径对应的集数，筛选出url不为空的数据，返回url顺序按参数urlNames顺序排序
	 * @param episodes 动漫数据
	 * @param urlNames 需要的url的名称
	 * @return 动漫对应的集数数据url名称级对应的动漫num、name、episodeId
	 */
	public static LinkedHashMap<String,ArrayList<HashMap<String,String>>> getEpisodeUrls(List<Episode> episodes,String... urlNames)
	{
		LinkedHashMap<String,ArrayList<HashMap<String,String>>> episodeUrls = new LinkedHashMap<String,ArrayList<HashMap<String,String>>>();
		for(String urlName : urlNames)
		{
			ArrayList<HashMap<String,String>> urls = new ArrayList<HashMap<String,String>>();
			for(Episode e : episodes)
			{
				if(e.getStr(urlName)!=null&&!"".equals(e.getStr(urlName)))
				{
					HashMap<String,String> urlMap = new HashMap<String,String>();
					urlMap.put("num", e.getInt("num").toString());
					urlMap.put("name", e.getStr("name"));
					urlMap.put("episodeId", e.getInt("id").toString());
					urls.add(urlMap);
				}
				episodeUrls.put(urlName, urls);
			}
		}
		return episodeUrls;
	}
}
